﻿/*
 * Copyright 2014 Francois Karman
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using Quartz.Ext;
using System;
using System.Net.Mail;

namespace Quartz.WebManager.BasicTasks
{
    /// <summary>
    /// Base class for the jobs that provides an alert system in case of job failure.
    /// </summary>
    [Property("errorEmails", PropertyTypes.String, DisplayName = "Error emails", Description = "Emails addresses to warn in case of an error - separated by semi-colons")]
    public abstract class BaseJob : IJob
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseJob"/> class.
        /// </summary>
        protected BaseJob()
        { }

        /// <summary>
        /// Executes the job and catch any error to send an email, if required.
        /// </summary>
        /// <param name="context">The execution context.</param>
        public void Execute(IJobExecutionContext context)
        {
            string errorEmails = context.MergedJobDataMap.GetString("errorEmails");

            try
            {
                this.ProtectedExecute(context);
            }
            catch (Exception exception)
            {
                this.SendError(context, exception, errorEmails);
                throw;
            }
        }

        /// <summary>
        /// Implements the job execution.
        /// </summary>
        /// <param name="context">The execution context.</param>
        protected abstract void ProtectedExecute(IJobExecutionContext context);

        /// <summary>
        /// Send an email with the error detail to some specified recipients.
        /// </summary>
        /// <param name="context">The execution context.</param>
        /// <param name="exception">The raised exception.</param>
        /// <param name="errorEmails">The emails that should be informed of the failure.</param>
        private void SendError(IJobExecutionContext context, Exception exception, string errorEmails)
        {
            if (string.IsNullOrEmpty(errorEmails))
            {
                return;
            }

            using (MailMessage message = new MailMessage())
            using (SmtpClient client = new SmtpClient())
            {
                message.To.Add(errorEmails);
                message.Subject = string.Format("An error occurs for the job {0}", context.JobDetail.Key.ToString());
                client.Send(message);
            }
        }
    }
}
